package com.imooc.Controller;

import com.imooc.Dao.GirlDao;
import com.imooc.Service.GirlService;
import com.imooc.domain.Girl;
import com.imooc.domain.Result;
import com.imooc.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created  on 18-6-28 下午2:37.
 * 作者: Dengjb
 * 说明:
 */
@RestController
public class GirlController {


	@Autowired
	private GirlDao girlDao;
	@Autowired
	private GirlService girlService;

	@GetMapping(value = "/girlList")
	public List<Girl> girlList(){
//		logger.info("girlList");
		return girlDao.findAll();
	}
	@GetMapping(value = "/insert")
	public void save(@RequestParam(value = "name") String name,
	                 @RequestParam(value = "age") Integer age){
		Girl girl = new Girl();
		girl.setAge(age);
		girl.setName(name);
		Girl save = girlDao.save(girl);
		System.out.print(save);
	}
	@GetMapping(value = "/getone")
	public Girl get(@RequestParam(value = "id") Integer id ){
		Girl one = girlDao.findOne(id);
		return one;
	}
	@GetMapping(value = "/deleteone")
	public void delete(@RequestParam(value = "id") Integer id ){
		girlDao.delete(id);
	}
	@GetMapping(value = "/findByAge")
	public List<Girl> findByAge(@RequestParam(value = "age") Integer age ){
		List<Girl> girls = girlDao.findByAge(age);
		return girls;
	}
	@GetMapping(value = "/saveTwo")
	public void saveTwo(){
		girlService.saveTwo();
	}

	@PostMapping(value = "/insertValid")
	public Result insertValid(@Valid Girl girl, BindingResult bindingResult){

		if(bindingResult.hasErrors()){
			return null;
//			return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
		}
		Girl save = girlDao.save(girl);
		return ResultUtil.success(save);
	}
	@GetMapping(value = "/getAge/{id}")
	public void getAge(@PathVariable("") Integer id) throws Exception{
		girlService.getAge(id);
	}

}
